import configparser
import json

from kazoo.client import KazooClient

import time


class zkback:
    def __init__(self, path='./config.ini'):
        self.initConfig(path)
        self.create_zk_Client()
        self.nodeBk = []

    def initConfig(self, path='conf'):
        cf = configparser.ConfigParser()
        cf.read(path)
        self.url = cf.get('zk', 'url')

    def setConfig(self, zkNode='/'):
        ck = configparser.ConfigParser()
        node = "node"
        node_data = "node_data"
        node_acls = "node_acls"
        ck.add_section("zk")
        ck.add_section(node)
        ck.add_section(node_data)
        ck.add_section(node_acls)
        ck.set('zk', 'url', '')
        data = self.get_zk_node(zkNode)
        i = 0
        for d in data:
            key = str(i)
            i += 1
            ck.set(node, key, d[node])
            ck.set(node_data, key, str(d[node_data]).replace("%", "%%"))
            ck.set(node_acls, key, d[node_acls])
        ti = time.strftime('%Y%m%d%H%M%S', time.localtime())
        ck.write(open("../history/config" + ti + ".ini", "w", encoding="utf-8"))

    def create_zk_Client(self):
        self.zk = KazooClient(self.url)
        self.zk.start()
        print("connent success")

    def get_zk_nodes_paths(self, zkNode='/'):
        cli = self.zk
        paths = []
        pts = [zkNode]
        while (len(pts) > 0):
            tp = []
            p = pts[0]
            ks = cli.get_children(p)
            for k in ks:
                ps = p + str(k) + '/'
                tp.append(ps)
                paths.append(ps)
            del pts[0]
            pts.extend(tp)
        return paths

    def get_zk_node(self, zkNode='/'):
        nodes = []
        cli = self.zk
        paths = self.get_zk_nodes_paths(zkNode)
        for path in paths:
            node = cli.get(path)
            if node[1].ephemeralOwner != 0:
                continue
            acl = cli.get_acls(path)[0]
            dt = {}
            dt["node"] = path
            dt["node_data"] = str(node[0], encoding='utf-8')
            aclMap = {}
            aclMap['perms'] = acl[0].perms
            aclMap['scheme'] = acl[0].id.scheme
            aclMap['id'] = acl[0].id.id
            dt["node_acls"] = json.dumps(aclMap)
            nodes.append(dt)
        return nodes


if __name__ == '__main__':
    c = zkback()
    c.setConfig('/datalake/')
